package com.qire.manhua.dialog;

import android.content.Context;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.qire.antsrouter.AntsRouter;
import com.qire.antsrouter.card.FloorCard;
import com.qire.common.constant.CustomEvent;
import com.qire.common.constant.Navigation;
import com.qire.common.model.entity.UserEntity;
import com.qire.common.support.base.BaseDialog;
import com.qire.common.utils.EquipmentInfoUtil;
import com.qire.common.utils.NoticeEventBus;
import com.qire.common.utils.NoticeEventBus.NoticeEvent;
import com.qire.common.utils.NoticeEventBus.EventSubscriber;
import com.qire.common.utils.ThemeUtil;
import com.qire.common.utils.ToastHelper;
import com.qire.common.widget.animation.SimpleAnimationUtil;
import com.qire.manhua.R;
import com.qire.manhua.activity.helper.LoginRouter;
import com.qire.manhua.controller.ComicReaderController;
import com.qire.manhua.databinding.DialogUnlockChapterOnComicReaderBinding;
import com.qire.manhua.model.viewModel.impl.UnlockChapterDialogViewModel;
import com.qire.other.recorder.ComicActionRecorder;

import androidx.annotation.NonNull;

/**
 * 在漫画阅读器中的解锁章节对话框 - 只适用于 ComicReaderActivity
 * @see com.qire.manhua.activity.ComicReaderActivity
 */
public class UnlockChapterOnComicReaderDialog extends BaseDialog {

    public static UnlockChapterOnComicReaderDialog build(Context context, UnlockChapterDialogViewModel unlockDialogViewModel, ComicReaderController controller) {
        return new UnlockChapterOnComicReaderDialog(context, unlockDialogViewModel, controller);
    }

    private final DialogUnlockChapterOnComicReaderBinding viewDataBinder;
    private final UnlockChapterDialogViewModel viewModel;
    private final ComicReaderController controller;

    private UnlockChapterOnComicReaderDialog(@NonNull Context context, UnlockChapterDialogViewModel viewModel, ComicReaderController controller) {
        super(context, R.style.FullDialog);

        this.viewModel = viewModel;
        this.controller = controller;

        viewDataBinder = DialogUnlockChapterOnComicReaderBinding.inflate(LayoutInflater.from(context));
        viewDataBinder.setUnlockChapterOnComicReaderDialog(this);
        viewDataBinder.setUnlockChapterDialogViewModel(viewModel);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        final int MATCH_PARENT = ViewGroup.LayoutParams.MATCH_PARENT;
        setContentView(viewDataBinder.getRoot(), new ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT));
        ThemeUtil.setWindowGravityBottom(getWindow(), MATCH_PARENT);
    }

    private static long dismissTime;
    @Override
    public void show() {
        if (viewModel.isInsufficientBalanceByPanel() && !viewModel.isInsufficientBalance()) {
            togglePanelBtnOnClick(null);
            viewModel.tipsAutoSwitch();
        }

        viewModel.refresh();
        long nowTime = System.currentTimeMillis();
        if (nowTime - dismissTime > 500) {
            refreshPanelTitle();
            super.show();
            viewDataBinder.panelFrame.setVisibility(View.VISIBLE);
            viewDataBinder.panelFrame.setAnimation(SimpleAnimationUtil.moveToViewLocation(200, null));
            SimpleAnimationUtil.playAnimationOnView(getContext(), R.anim.app_quick_read_topbar_in, viewDataBinder.titleNavBar);
        }
    }

    @Override
    public void dismiss() {
        viewDataBinder.panelFrame.setVisibility(View.GONE);
        viewDataBinder.panelFrame.setAnimation(SimpleAnimationUtil.moveToViewBottom(200, null));
        viewDataBinder.panelFrame.postDelayed(() -> {
            super.dismiss();
            dismissTime = System.currentTimeMillis();
        },201);
        SimpleAnimationUtil.playAnimationOnView(getContext(), R.anim.app_quick_read_topbar_out,
                viewDataBinder.titleNavBar, animation -> viewDataBinder.titleNavBar.setVisibility(View.GONE));
    }

    /**
     * 刷新面板标题栏
     */
    private void refreshPanelTitle() {
        if(viewModel.isBeanUnlockPanel()) {
            viewDataBinder.balancePanelTitle.setTextColor(Color.rgb(0x66,0x66,0x66));
            viewDataBinder.balancePanelTitle.setTypeface(Typeface.DEFAULT);
            ((ViewGroup.MarginLayoutParams) viewDataBinder.balancePanelTitle.getLayoutParams()).topMargin = EquipmentInfoUtil.dip2px(10);
            viewDataBinder.vipPanelTitle.setTextColor(Color.rgb(0x00,0x00,0x00));
            viewDataBinder.vipPanelTitle.setTypeface(Typeface.DEFAULT_BOLD);
            ((ViewGroup.MarginLayoutParams) viewDataBinder.vipPanelTitle.getLayoutParams()).topMargin = EquipmentInfoUtil.dip2px(0);
        } else {
            viewDataBinder.vipPanelTitle.setTextColor(Color.rgb(0x66,0x66,0x66));
            viewDataBinder.vipPanelTitle.setTypeface(Typeface.DEFAULT);
            ((ViewGroup.MarginLayoutParams) viewDataBinder.vipPanelTitle.getLayoutParams()).topMargin = EquipmentInfoUtil.dip2px(10);
            viewDataBinder.balancePanelTitle.setTextColor(Color.rgb(0x00,0x00,0x00));
            viewDataBinder.balancePanelTitle.setTypeface(Typeface.DEFAULT_BOLD);
            ((ViewGroup.MarginLayoutParams) viewDataBinder.balancePanelTitle.getLayoutParams()).topMargin = EquipmentInfoUtil.dip2px(0);
        }
    }

    public void closeLayoutOnClick(View view) {
        // 不使用 (dismiss()) 而使用 (cancel()) 会触发调用 OnCancelListener 监听，
        // 因为 {@code OnCancelListener} 里有从外部直接进入阅读页时取消对话框需要处理的额外行为，如：退出阅读页。
        cancel();
    }

    public void detailsDirectoryBtnOnClick(View view) {
        AntsRouter.ROUTER.<FloorCard>buildCard(Navigation.Page.ComicDetailPage)
                .withData("comicBookId", viewModel.comicBookId())
                .withData("pageNo", 1)
                .navigation();
        dismiss();
    }

    public void togglePanelBtnOnClick(View view) {
        viewModel.toggleUnlockPanelTabs();
        refreshPanelTitle();
    }

    public void noLongerRemindOnClick(View view) {
        viewModel.noLongerRemind();
        viewModel.toggleUnlockPanel();
    }

    public void buyMembershipBtnOnClick(View view) {
        AntsRouter.ROUTER.buildCard(Navigation.Page.BuyMembershipDialogPage).navigation();
        dismiss();
    }

    public void toggleUnlockPanelBtnOnClick(View view) {
        viewModel.toggleUnlockPanel();
    }

    public void unlockByAdBtnOnClick(View view) {
        if(!UserEntity.self.canAdUnlocked()) {
            ToastHelper.showToast("今日广告解锁次数已用完，明天再来哦！");
            return;
        }
        view.setTag(viewModel);
        controller.unlockByAdBtnOnClick(view);
        dismiss();
    }

    public void unlockBtnOnClick(View view){
        if(viewModel.isInsufficientBalanceByPanel()) {
            AntsRouter.ROUTER.<FloorCard>buildCard(Navigation.Page.BuyCoinsMarketDialogPage)
                    .withData("comicId", viewModel.comicBookId())
                    .navigation();
            // 行为数据统计
            ComicActionRecorder.build(ComicActionRecorder.count_recharge_show)
                    .setSource("阅读页充值浮层")
                    .doRecorde(getContext());
        } else {
            view.setTag(viewModel);
            controller.unlockByBuyBtnOnClick(view);
        }
        dismiss();
    }

    public void loginBtnOnClick(View view) {
        NoticeEventBus.NOTICE.unSubscribeEvent(loginSuccessEventSubscriber);
        NoticeEventBus.NOTICE.subscribeEvent(CustomEvent.LOGIN_SUCCESS, loginSuccessEventSubscriber);
        LoginRouter.ROUTER.checkLoginRouteIfNeed();
    }

    public void directoryBtnOnClick(View view) {
//        ToastHelper.showToast("目录");
        controller.directoryBtnOnClick(view);
        dismiss();
    }

    private void closeDialog() {
        NoticeEventBus.NOTICE.unSubscribeEvent(loginSuccessEventSubscriber);
        postDismiss();
    }
    private EventSubscriber loginSuccessEventSubscriber = (NoticeEvent event) -> {
        closeDialog();
        return false;
    };

}
